package com.gitee.ykr.lightweight.rpc.loadbalance;

import com.gitee.ykr.lightweight.rpc.common.entity.NettyClient;
import com.gitee.ykr.lightweight.rpc.registar.RpcClientEntity;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author YKR
 * @Describe
 * @date 2021/8/24
 */
public class RandomLoadBalanceExecutor extends AbstractLoadBalanceExecutor {

    @Override
    protected RpcClientEntity loadBalance(RpcClientEntity rpcClientEntity , String interfaceName, List<NettyClient> candidates) {
        if (candidates == null || candidates.size() == 0) {
            return null;
        }
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        int index = threadLocalRandom.nextInt( candidates.size() );
        NettyClient nettyClient=candidates.get( index );
        RpcClientEntity entity=new RpcClientEntity();
        BeanUtils.copyProperties( nettyClient,entity );
        entity.setIsSyn( rpcClientEntity.isSyn() );
        entity.setRpcClz( rpcClientEntity.getRpcClz() );
        return entity;
    }
}
